package com.dap.core.config;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.core.io.AbstractResource;


public class ConfigSvrResource extends AbstractResource {
    private String location;
    private String extName;
    private ByteArrayOutputStream baos = null;


    public ConfigSvrResource(String location) throws IOException {
        boolean needToStore = location.endsWith("#");
        if (needToStore) {
            this.location = location.substring(0, location.length() - 1);
        } else {
            this.location = location;
        }
        InputStream is = getInputStream();
        if (needToStore) {
            storeToFile(is);
        }
        is.close();
    }


    private void storeToFile(InputStream is) throws IOException {
        File f = new File(System.getProperty("user.dir") + File.separator + this.location);
        File p = f.getParentFile();
        if (!p.exists()) {
            p.mkdirs();
        }
        if (!f.exists()) {
            f.createNewFile();
        }
        FileOutputStream os = new FileOutputStream(f);
        int data = -1;
        while ((data = is.read()) != -1) {
            os.write(data);
        }
        os.flush();
        os.close();
    }


    @Override
    public String getFilename() {
        return this.location;
    }


    @Override
    public boolean exists() {
        return true;
    }


    @Override
    public boolean isOpen() {
        return true;
    }


    @Override
    public String getDescription() {
        StringBuilder sb = new StringBuilder("configsvr resource[");
        sb.append(this.location).append("]");
        return sb.toString();
    }


    @Override
    public InputStream getInputStream() throws IOException {
        if (this.baos == null) {
            InputStream inputStream = retrieveFromConfigsvr();
            refresh(inputStream);
            inputStream.close();
        }
        return new ByteArrayInputStream(this.baos.toByteArray());
    }


    private void refresh(InputStream inputStream) throws IOException {
        this.baos = new ByteArrayOutputStream();
        byte[] buffer = new byte['Ѐ'];
        int len;
        while ((len = inputStream.read(buffer)) > -1) {
            this.baos.write(buffer, 0, len);
        }
        this.baos.flush();
    }


    public String getConfigString() {
        return this.baos.toString();
    }


    private InputStream retrieveFromConfigsvr() {
        return ConfigServerClientFactory.getConfigServerClient().getConfigContent(this.location);
    }


    public String getExtName() {
        return this.extName;
    }


    public void setExtName(String extName) {
        this.extName = extName;
    }
}
